<template>
  <div>
    <el-form ref="formRef" :model="formData" label-width="100px" :rules="formRules">
      <el-row :gutter="22">
        <el-col :span="11" class="form-item-col">
          <el-form-item label="集群名称" prop="cluster_name">
            <el-input v-model="formData.cluster_name" type="text" autoComplete="off"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="11">
          <el-form-item label="心跳数量" prop="hb_number">
            <el-select v-model="hb_number" @change="handleChangeHbNum">
              <el-option v-for="num in 7" :key="num" :label="num + '路'" :value="num" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <p class="tip">注：节点密码为hacluster用户密码！</p>
      <div class="create-cluster">
        <div v-for="(nodeItem, index) in formData.data" :key="index">
          <div class="node-line">
            <el-row :gutter="24">
              <el-col :span="12">
                <el-form-item
                  :label="`节点名称${index + 1}`"
                  :prop="`data.${index}.name`"
                  :rules="formRules.data.name">
                  <el-input v-model="nodeItem.name" type="text" autoComplete="off"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item
                  :label="`节点密码${index + 1}`"
                  :prop="`data.${index}.password`"
                  :rules="formRules.data.password">
                  <input-pwd v-model="nodeItem.password" />
                </el-form-item>
              </el-col>
              <!-- 心跳循环 -->
              <el-col :span="12" v-for="(ip, ipIndex) in nodeItem.ips" :key="ipIndex">
                <el-form-item
                  :label="`IP地址 ${ipIndex + 1}`"
                  :prop="`data.${index}.ips.${ipIndex}.value`"
                  :rules="getRingAddrRules(index, ipIndex)">
                  <div style="display: flex; gap: 10px">
                    <el-input
                      v-model="ip.value"
                      type="text"
                      autoComplete="off"
                      @input="handleIpChange(index, ipIndex)" />
                  </div>
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 删除节点 -->
            <span class="del-node" @click="handleDelNode(index)">X</span>
          </div>
        </div>
      </div>

      <el-button class="add-node" @click="handleAddNode">
        <span class="iconfont icon-tianjia"></span>
        添加节点
      </el-button>
    </el-form>

    <div class="dialog-footer">
      <el-button @click="handleDialogClose">取消</el-button>
      <el-button type="primary" @click="submitForm" :loading="loading">确定</el-button>
    </div>
  </div>
</template>

<script>
import InputPwd from '@/components/InputPwd.vue'
import { createCluster } from '@/api/clusterOverview'
import { vd } from '@/utils/validate'

export default {
  name: 'CreateCluster',
  components: {
    InputPwd,
  },
  props: {
    clusterNames: {
      type: Array,
      default: () => {
        return []
      },
    },
    ips: {
      type: Array,
      default: () => {
        return []
      },
    },
  },
  data() {
    // 自定义校验 - 检查IP地址是否重复
    const validateIpUnique = (rowIndex, addrIndex) => {
      return (rule, value, callback) => {
        if (!value) {
          callback()
          return
        }
        let isDuplicate = false

        this.formData.data.forEach((row, rIndex) => {
          row.ips.forEach((addr, aIndex) => {
            // 跳过自身
            if (rIndex === rowIndex && aIndex === addrIndex) return

            if (addr.value === value) {
              isDuplicate = true
            }
          })
        })

        if (isDuplicate || this.ips.includes(value)) {
          callback(new Error('输入的IP地址已存在！'))
        } else {
          callback()
        }
      }
    }

    // 自定义校验 - 检查集群名称是否重复
    const validateClusterNameUnique = (rule, value, callback) => {
      if (this.clusterNames.includes(value)) {
        callback(new Error('集群名称已存在！'))
      } else {
        callback()
      }
    }

    return {
      formData: {
        cluster_name: '',
        data: [],
      },
      formRules: {
        cluster_name: [
          vd.required,
          vd.length(1, 32),
          vd.nodeName,
          { validator: validateClusterNameUnique, trigger: ['change', 'blur'] },
        ],
        data: {
          name: [vd.required, vd.length(1, 50), vd.nodeName],
          password: [vd.required, vd.length(8, 50), vd.pwd],
        },
      },
      hb_number: 2,
      loading: false,
      validateIpUnique, // 保存到 data 中以便在 methods 中使用
    }
  },
  mounted() {
    // 初始化 两个节点信息，IP为两个
    for (let index = 0; index < 2; index++) {
      this.formData.data.push({
        name: '',
        password: '',
        ips: [{ value: '' }, { value: '' }],
      })
    }
  },
  methods: {
    // 获取环地址校验规则
    getRingAddrRules(rowIndex, addrIndex) {
      return [
        vd.required,
        vd.ip,
        { validator: this.validateIpUnique(rowIndex, addrIndex), trigger: ['change', 'blur'] },
      ]
    },

    // IP地址变更处理，对其它ip值重新校验
    handleIpChange(changedRowIndex, changedAddrIndex) {
      if (!this.$refs.formRef) return

      // 延迟执行以确保值已更新
      this.$nextTick(() => {
        // 获取需要重新校验的字段
        const fieldsToValidate = []

        this.formData.data.forEach((row, rowIndex) => {
          row.ips.forEach((addr, addrIndex) => {
            // 跳过自身
            if (rowIndex === changedRowIndex && addrIndex === changedAddrIndex) return

            // 只有当IP值存在才重新校验
            if (addr.value) {
              fieldsToValidate.push(`data.${rowIndex}.ips.${addrIndex}.value`)
            }
          })
        })

        // 触发相关字段的重新校验
        if (fieldsToValidate.length > 0) {
          this.$refs.formRef.validateField(fieldsToValidate)
        }
      })
    },

    // 改变心跳路数
    handleChangeHbNum(value) {
      console.log('value', value, typeof value)
      // 判断 已有心跳路数 与 选择的心跳路数的大小
      let oldHB = this.formData.data[0].ips.length
      let diff = value - oldHB
      // 添加IP
      if (diff >= 0) {
        this.formData.data.forEach((item) => {
          for (let index = 0; index < diff; index++) {
            item.ips.push({ value: '' })
          }
        })
      } else {
        // 删除IP
        console.log('diff', diff)
        this.formData.data.forEach((item) => {
          item.ips = item.ips.slice(0, diff)
        })
      }
      // 修改心跳路数，清除校验
      this.$refs.formRef.clearValidate()
    },

    // 删除节点
    handleDelNode(index) {
      console.log('index', index)

      if (this.formData.data.length === 2) {
        this.$message.warning('无法创建单节点集群!')
      } else {
        this.formData.data.splice(index, 1)
      }
    },

    // 添加节点
    handleAddNode() {
      let hbArr = []

      for (let index = 0; index < this.hb_number; index++) {
        hbArr.push({ value: '' })
      }

      this.formData.data.push({
        name: '',
        password: '',
        ips: hbArr,
      })
    },

    // 表单提交
    submitForm() {
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          this.loading = true
          let data = []
          this.formData.data.forEach((item, index) => {
            let ringAddr = []

            item.ips.forEach((ip) => {
              ringAddr.push(ip.value)
            })

            data.push({
              name: item.name,
              password: item.password,
              nodeid: index,
              ring_data: ringAddr,
            })
          })

          createCluster({ cluster_name: this.formData.cluster_name, data })
            .then((res) => {
              this.loading = false
              if (res.data.action) {
                this.$message.success(res.data.info)
                this.$emit('click', 'success')
              } else {
                this.$message.error(res.data.error)
                this.$emit('click')
              }
            })
            .catch(() => {
              this.loading = false
              this.$emit('click')
            })
        }
      })
    },

    // 取消
    handleDialogClose() {
      // 使用 resetFields 重置表单
      this.$refs.formRef.resetFields()
      this.$emit('click')
    },
  },
}
</script>

<style lang="scss" scoped>
.create-cluster {
  max-height: 400px;
  overflow-y: auto;
}

.tip {
  color: #f5222d;
  padding-bottom: 6px;
}

.node-line {
  padding: 16px 10px 0;
  position: relative;
  margin-bottom: 10px;
  border: 1px solid #ded4d4;
}

.del-node {
  position: absolute;
  top: 8px;
  right: 8px;
  cursor: pointer;
  color: #f56c6c;
  font-size: 18px;
  font-weight: bold;
  width: 24px;
  height: 24px;
  line-height: 24px;
  text-align: center;
  border-radius: 50%;
  transition: all 0.3s;

  &:hover {
    background-color: #f56c6c;
    color: white;
  }
}

.add-node {
  color: green;
}

.dialog-footer {
  margin-top: 20px;
  text-align: right;
}
</style>
